package cn.car91.config;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;
import cn.car91.activity.BaseActivity;
import cn.car91.http.HttpHandler;
import cn.car91.service.UpdateService;

import com.lidroid.xutils.util.LogUtils;

public class GlobalException implements UncaughtExceptionHandler {
    private DateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private static GlobalException myCrashHandler;
    private Context context;

    private GlobalException() {
    }

    public static synchronized GlobalException getInstance() {
        if (myCrashHandler == null) {
            myCrashHandler = new GlobalException();
        }
        return myCrashHandler;
    }

    public void init(Context ctx) { // 初始化，把当前对象设置成UncaughtExceptionHandler处理器
        this.context = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3 * 1000);
            } catch (InterruptedException e) {
            }
            //退出程序
            UpdateService.isFirst = true;
            Intent intent = new Intent();
            intent.setAction(BaseActivity.exitAction);
            context.sendBroadcast(intent);
            System.exit(0);
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast toast = Toast.makeText(context, "（╯‘□′）╯)┴—┴，\r\nApp出错了，即将退出", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                Looper.loop();
            }
        }.start();
        try {
            if (((InitApplication) context).getSetPreferences().getBoolean("pushlog", true))
                saveCrashInfo2File(ex);
        } catch (Exception e) {
        }

        return true;
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     */
    private void saveCrashInfo2File(Throwable ex) {
        String time = dataFormat.format(new Date());
        StringBuffer sb = new StringBuffer();
        sb.append(time + "   手机型号：" + Build.MODEL + "   系统：" + Build.DISPLAY + "\r\n");
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        try {
            HttpHandler.httpHandler.pushLog(sb.toString());
        } catch (Exception e) {
            LogUtils.e("an error occured while writing file...", e);
        }
    }
}
